<?php

namespace app\index\controller;

use AlibabaCloud\Client\Support\Sign;
use app\common\model\MemberModel;
use app\common\model\TeacherModel;
use app\index\validate\Password;
use app\index\validate\SignUp;
use think\Db;

class LoginController extends BaseController
{
    public function index()
    {
        return $this->fetch('sign_in');
    }

    public function login()
    {
        if (is_mobile()){
            return $this->fetch('/mobile/login/sign_in');
        }
        return $this->fetch('sign_in');
    }

    public function doLogin()
    {
        $param = $this->request->param();
        if ($this->request->isPost()){
            if (!isset($param['account'])){
                $res['code'] = 0;
                $res['msg'] = '请输入手机号或工号';
                return json($res);
            }
            if (!isset($param['password'])){
                $res['code'] = 0;
                $res['msg'] = '请输入密码';
                return json($res);
            }
        $account = $param['account'];
        $captcha = $this->request->param('code');
        // 验证码
        if (! check_captcha($captcha)) {
            $res['code'] = 0;
            $res['msg'] = '验证码错误';
            return json($res);
        }
        if (isPhoneNumber($account)) { // 普通用户手机号登录
            $passwd = $param['password'];
            $member = MemberModel::where("phone", $account)->find();
            if ($member){
                if (compare_password($passwd, $member['password'])) {
                    Db::name("login_log")->insert(['phone'=>$member['phone'],'user_type'=>1,'ip'=>get_client_ip()]);
                    session('userInfo', json_encode($member));
                    session('user_type', 1);
                    session('uid', $member['id']);
                    cookie('uid', $member['id']);
                    cookie('user_type', 1);
                    $res['code'] = 1;
                    $res['msg'] = '登录成功';
                    return json($res);
                } else {
                    $res['code'] = 0;
                    $res['msg'] = '密码错误';
                    return json($res);
                }
            } else {
                $res['code'] = 0;
                $res['msg'] = '账号或密码错误';
                $res['member'] = $member;
                $res['param'] = $param;
                return json($res);
            }
        } else { // 老师用户使用工号登录
            $passwd = $param['password'];
            $teacher = TeacherModel::where("teacher_no", $account)->find();
            if ($teacher) {
                if (compare_password($passwd, $teacher['password'])) {
                    Db::name("login_log")->insert(['teacher_no'=>$teacher['teacher_no'],'user_type'=>1,'ip'=>get_client_ip()]);
                    session('userInfo', json_encode($teacher));
                    session('user_type', 0);
                    session('uid', $teacher['id']);
                    cookie('uid', $teacher['id']);
                    cookie('user_type', 0);

                    $res['code'] = 1;
                    $res['msg'] = '登录成功';
                    return json($res);
                } else {
                    $res['code'] = 0;
                    $res['msg'] = '密码错误';
                    return json($res);
                }
            } else {
                $res['code'] = 0;
                $res['msg'] = '账号或密码错误';
                $res['param'] = $param;
                $res['isphone'] = isPhoneNumber($account);
                return json($res);
            }
        }

        }else{
            $res['code'] = 0;
            $res['msg'] = '不支持的请求方式';
            return json($res);
        }
    }

    public function logout()
    {
        session('userInfo', null);
        session('user_type', null);
        session('uid', null);
        cookie('uid', null);
        cookie('user_type', null);
        $res['code'] = 1;
        $res['msg'] = '已退出登录';
        return json($res);
    }

    public function mlogout()
    {
        session('userInfo', null);
        session('user_type', null);
        session('uid', null);
        cookie('uid', null);
        cookie('user_type', null);
        $res['code'] = 1;
        $res['msg'] = '已退出登录';
        return $this->redirect("/index/index");
    }


    public function resetPassword()
    {
        $user = json_decode(session('userInfo'), true);
        if ($user) {
            $param = $this->request->param();

            $validate = new Password();
            if (!$validate->check($param)) {
                $res['code'] = 0;
                $res['msg'] = $validate->getError();
                return $res;
            }
            $issuer_type = isset($user['teacher_no']) ? 0 : 1;
            if ($issuer_type == 0) {
                $teacher = TeacherModel::where('id', $user['id'])->find();
                if (compare_password($param['oldPass'], $teacher['password'])) {
                    $newPass = $param['newPass'];
                    $update = TeacherModel::where('id', $user['id'])->update(['password' => password($newPass)]);
                    if ($update !== false) {
                        $res['code'] = 1;
                        $res['msg'] = '修改成功';
                    } else {
                        $res['code'] = 0;
                        $res['msg'] = '修改失败，请重试';
                    }
                } else {
                    $res['code'] = 0;
                    $res['msg'] = '旧密码输入错误';

                }
            } else {
                $teacher = MemberModel::where('id', $user['id'])->find();
                if (compare_password($param['oldPass'], $teacher['password'])) {
                    $newPass = $param['newPass'];

                    $update = MemberModel::where('id', $user['id'])->update(['password' => password($newPass)]);
                    if ($update !== false) {
                        $res['code'] = 1;
                        $res['msg'] = '修改成功';
                    } else {
                        $res['code'] = 0;
                        $res['msg'] = '修改失败，请重试';
                    }
                } else {
                    $res['code'] = 0;
                    $res['msg'] = '旧密码输入错误';

                }
            }
            return $res;
        } else {
            $this->redirect('index/index');
        }
    }

    public function signUp(){
        if (is_mobile()){
            return $this->fetch('/mobile/login/sign_up');
        }
        return $this->fetch();
    }

    public function doSignUp(){
        $param = $this->request->param();
        $validate = new SignUp();
        if (!$validate->check($param)) {
            $res['code'] = 0;
            $res['msg'] = $validate->getError();
            return $res;
        }

        $codeCheck = checkPhoneCode($param['phone'],$param['code']);
        if ($codeCheck === false){
            $res['code'] = 0;
            $res['msg'] = '验证码错误';
            return $res;
        }

        if ($codeCheck === -1){
            $res['code'] = 0;
            $res['msg'] = '验证码已过期';
            return $res;
        }

        $checkMember = MemberModel::where('phone',$param['phone'])->find();
        if ($checkMember){
            $res['code'] = 0;
            $res['msg'] = '手机号已注册';
            return $res;
        }else{
            unset($param['code']);
            unset($param['password_confirm']);
            $param['password'] = password($param['password']);
            $memberId = Db::name('member')->insertGetId($param);
            if ($memberId !== false){
                $res['code'] = 1;
                $res['msg'] = '注册成功';
                return $res;
            }else{
                $res['code'] = 0;
                $res['msg'] = '注册失败';
                return $res;
            }
        }
    }
    public function doResetPwd(){
        $param = $this->request->param();
        $validate = new SignUp();
        if (!$validate->check($param)) {
            $res['code'] = 0;
            $res['msg'] = $validate->getError();
            return $res;
        }

        $codeCheck = checkPhoneCode($param['phone'],$param['code']);
        if ($codeCheck === false){
            $res['code'] = 0;
            $res['msg'] = '验证码错误';
            return $res;
        }

        if ($codeCheck === -1){
            $res['code'] = 0;
            $res['msg'] = '验证码已过期';
            return $res;
        }

        $checkMember = MemberModel::where('phone',$param['phone'])->find();
        if ($checkMember){
            $result = MemberModel::where('id',$checkMember['id'])->update(['password'=>password($param['password'])]);
            if ($result === false){
                $res['code'] = 0;
                $res['msg'] = '修改失败，请重试';
                return $res;
            }else{
                $res['code'] = 1;
                $res['msg'] = '修改成功';
                return $res;
            }
        }else{
            $res['code'] = 0;
            $res['msg'] = '手机号未注册';
            return $res;
        }
    }

    public function sendCode(){
        $param = $this->request->param();
        if (empty($param['phone'])){
            $res['code'] = 0;
            $res['msg'] = '请输入手机号';
            return $res;
        }

        if (! check_captcha($param['code'])) {
            $res['code'] = 0;
            $res['msg'] = '验证码错误';
            return json($res);
        }

        $res['code'] = 1;
        $res['msg'] = '发送成功';
        return json($res);

    }

    public function forgetPwd(){
        if (is_mobile()){
            return $this->fetch('/mobile/login/forget_pwd');
        }
        return $this->fetch('forget_pwd');
    }
}
